﻿/**
 * ...
 * @author krozalski
 */

package hapi.flash.display;
import flash.display.MovieClip;
import flash.display.Sprite;
import hapi.flash.util.AssetsUtil;

enum FrameBasedTextAlign {
	left;
	right;
}

class FrameBasedText extends Sprite {
	
	public var text(default, setText):String;
	public var textWidth(getTextWidth, null):Float;
	public var align(getAlign, setAlign):FrameBasedTextAlign;
	var textAlign:FrameBasedTextAlign;
	var maxLength:Int;
	var charSpriteClassName:String;
	var chars:Array<MovieClip>;
	var charWidth:Float;
	var currentText:String;
	
	public function new(maxLength:Int, className:String, ?charWidth:Float=0) {
		super();
		this.textAlign = FrameBasedTextAlign.left;
		this.maxLength = maxLength;
		this.charSpriteClassName = className;
		this.charWidth = charWidth;
		initChars();
		this.setText("");
	}
	
	function initChars() {
		chars = new Array<MovieClip>();
		for ( i in 0...maxLength ) {
			addChar(i);
		}
	}
	
	function addChar(i:Int) {
		var char:MovieClip = AssetsUtil.createSprite(charSpriteClassName);
		char.x = i * getCharWidth();
		chars.push(char);
		addChild(char);
	}
	
	function renderText(txt) {
		currentText = txt == null ? "" : txt;
		var offset = textAlign == FrameBasedTextAlign.left ? 0 : maxLength - currentText.length;
		for ( i in 0...maxLength ) {
			chars[i].visible = false;
		}
		for ( i in 0...currentText.length ) {
			var char = currentText.charAt(i);
			var c = chars[offset + i];
			c.gotoAndStop("s_"+char);
			c.visible = true;
		}
	}
	
	function setText(txt:String):String {
		txt = txt.substr(0, maxLength);
		renderText(txt);
		return txt;
	}
	
	function getAlign():FrameBasedTextAlign {
		return textAlign;
	}
	
	function setAlign(a:FrameBasedTextAlign):FrameBasedTextAlign {
		if(textAlign != a ){
			this.textAlign = a;
			renderText(this.text);
		}
		return textAlign;
	}
	
	function getCharWidth() {
		if (charWidth == 0 && chars.length > 0) {
			charWidth = chars[0].width;
		}
		return charWidth;
	}
	
	function getTextWidth() {
		return getCharWidth() * currentText.length;
	}
}